package com.xiaoniu.imclient.networkModule.rong;

import android.os.Parcel;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

import io.rong.common.ParcelUtils;
import io.rong.imlib.MessageTag;
import io.rong.imlib.model.MessageContent;


@MessageTag(value = "ChatRoom:QYTextMessage", flag = MessageTag.ISCOUNTED | MessageTag.ISPERSISTED)
public class MessageTextBean extends MessageContent {
    private String content;
    private int type;

    public static MessageTextBean obtain(String text) {
        MessageTextBean model = new MessageTextBean();
        model.setContent(text);
        return model;
    }

    private MessageTextBean() {
    }

    public MessageTextBean(Parcel in) {
        setContent(ParcelUtils.readFromParcel(in));
    }

    private void handlerMessages(String contentJson) {
        try {
            JSONObject object = new JSONObject(contentJson);
            type = object.optInt("type");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public MessageTextBean(byte[] data) {
        String jsonStr = null;
        try {
            jsonStr = new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
        }
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);
            if (jsonObj.has("content")) {
                setContent(jsonObj.optString("content"));
            }
        } catch (JSONException e) {
        }
    }

    public static final Creator<MessageTextBean> CREATOR = new Creator<MessageTextBean>() {

        @Override
        public MessageTextBean createFromParcel(Parcel source) {
            return new MessageTextBean(source);
        }

        @Override
        public MessageTextBean[] newArray(int size) {
            return new MessageTextBean[size];
        }
    };

    @Override
    public byte[] encode() {
        JSONObject jsonObj = new JSONObject();
        try {
            jsonObj.put("content", content);
        } catch (JSONException e) {
            Log.e("JSONException", e.getMessage());
        }

        try {
            return jsonObj.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int flags) {
        ParcelUtils.writeToParcel(parcel, content);
    }


    public String getContent() {
        return content;
    }

    public void setContent(String data) {
        this.content = data;
        handlerMessages(data);
    }


    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }



}
